import random

from django.db.models import Q
from django.views import View

from apps.book.models import Book, BookGroup
from apps.user.models import User_book

from django.conf import settings
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.shortcuts import render

from haystack.forms import FacetedSearchForm, ModelSearchForm
from haystack.query import EmptySearchQuerySet

RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 20)


class Index_view(View):
    def get(self, request):
        # 首页推荐数据
        book = Book.objects.all().order_by("-creat_time")[:34]
        # 编辑推荐数据
        book_tj = Book.objects.all().order_by("-status")[:7]
        # 获取分类数据
        group = BookGroup.objects.all().order_by("id")

        content = {
            "book": book,
            "book_tj": book_tj,
            "group": group,
            "t_f": request.user if request.user.id else None
        }
        return render(request, "index/index.html", context=content)


class All(View):
    def get(self, request):
        try:
            # 获取分类
            group_id = int(request.GET.get("group"))
            # 获取小说数据
            data = Book.objects.filter(group_id=group_id)
        except:
            group_id = None
            data = Book.objects.all()
        num = request.GET.get("num", "1")
        if num.isdigit():
            num = int(num)
        else:
            num = 1

        #  获取所有分类
        group = BookGroup.objects.all()
        # 分页
        pg = Paginator(data, 10)
        # 获取分页数据
        pg_data = pg.page(num)

        pg_data.num_pages = pg.num_pages
        content = {
            "pg": pg_data.object_list,
            "group": group,
            "group_id": group_id,
            "t_f": request.user if request.user.id else None,
            "page": pg_data
        }
        return render(request, "index/all.html", context=content)


class Rankings(View):
    def get(self, request):
        # 获取分类，
        group_id = request.GET.get("group")
        # 获取页数
        num = request.GET.get("num", "1")
        if num.isdigit():
            num = int(num)
        else:
            num = 1
        # 判断是否有分类， 如果没有则是查询所有
        if group_id and group_id.isdigit():
            book = Book.objects.filter(group_id=group_id).order_by("-creat_time")
        else:
            book = Book.objects.all().order_by("-creat_time")
        # 数据分页
        pg = Paginator(book, 10)
        # 获取分页数据可迭代对象
        book = pg.page(num).object_list
        # 获取所有分类
        group = BookGroup.objects.all()
        page = pg.page(num)
        page.num_pages = pg.num_pages
        content = {
            "book": book,
            "group_id": int(group_id) if group_id and group_id.isdigit() else None,
            "group": group,
            "num": num,
            "t_f": request.user if request.user.id else None,
            "page": page
        }
        return render(request, "index/ranking.html", context=content)


class Over(View):
    def get(self, request):
        # 获取小说数据
        try:
            group_id = int(request.GET.get("group"))
            data = Book.objects.filter(group_id=group_id, status=True).order_by("creat_time")
        except:
            group_id = None
            data = Book.objects.filter(status=True).order_by("creat_time")
        # 获取页数
        num = request.GET.get("num", "1")
        if num.isdigit():
            num = int(num)
        else:
            num = 1
        # 获取分类
        group = BookGroup.objects.all()
        # 获取分页
        pg = Paginator(data, 10)
        if pg.num_pages >= num:
            pg_data = pg.page(num).object_list
        else:
            pg_data = pg.page(1).object_list
        page = pg.page(num)
        page.num_pages = pg.num_pages
        content = {
            "pg": pg_data,
            "group": group,
            "group_id": group_id,
            "t_f": request.user if request.user.id else None,
            "page": page
        }
        return render(request, "index/over.html", context=content)


class Serial(View):
    def get(self, request):
        try:
            group_id = int(request.GET.get("group"))
            data = Book.objects.filter(group_id=group_id, status=False)
        except:
            group_id = None
            data = Book.objects.all().filter(status=False)
        num = request.GET.get("num", "1")
        if num.isdigit():
            num = int(num)
        else:
            num = 1
        # 获取分类
        group = BookGroup.objects.all()
        # 获取页数
        pg = Paginator(data, 10)
        # 提取当前页数
        if pg.num_pages >= num:
            pg_data = pg.page(num)
        else:
            pg_data = pg.page(1)
        pg_data.num_pages = pg.num_pages
        content = {
            "pg": pg_data.object_list,
            "group": group,
            "group_id": group_id,
            "t_f": request.user if request.user.id else None,
            "page": pg_data,
            "user": request.user if request.user.id else None
        }
        return render(request, "index/lianzai.html", context=content)


class Search(View):
    def get(self, request):
        search = request.GET.get("search", "")
        name = search
        book = []
        tj_book = []
        # 判断是否有查询值
        if search:
            # 查询值模糊查询
            book = Book.objects.filter(Q(name__contains=search) | Q(author=search))
            # 判断从数据库中出现出来的数据是否为空
            if not book:
                # 设置查询值为空
                search = ""
        # 判断查询值是否为空， 如果为空则为用户推荐一些数据
        if not search:

            # 判断用户是否登录， 如果登录，则从他的书架中获取他收藏最多类型的小说
            if request.user.id:
                book_info = User_book.objects.filter(user=request.user, is_del=False)
                lists = []
                for i in book_info:
                    lists.append(i.book.group_id)
                # 如果用户书架没有小说，则给他最新的小说
                if lists:
                    tj_book = Book.objects.filter(group_id=max(lists))[:6]
                else:
                    tj_book = Book.objects.all().order_by('-creat_time')[:6]
            # 如果用户没有登录， 则随机一些分类小说返回给用户
            else:
                num = random.randint(0, 9)
                # 0代表最新
                if num == 0:
                    tj_book = Book.objects.all().order_by('-creat_time')[:6]
                else:
                    tj_book = Book.objects.filter(group_id=num)[:6]
        right_tj = Book.objects.all().order_by("-creat_time")
        pg = Paginator(right_tj, 6)
        right_tj = pg.page(pg.num_pages - 1).object_list
        content = {
            "search": search,
            "book": book,
            "tj_book": tj_book,
            "right_tj": right_tj,
            "name": name
        }
        return render(request, "index/../../templates/search/search.html", context=content)


class SearchView(object):
    template = 'search/search.html'
    extra_context = {}
    query = ''
    results = EmptySearchQuerySet()
    request = None
    form = None
    results_per_page = RESULTS_PER_PAGE

    def __init__(self, template=None, load_all=True, form_class=None, searchqueryset=None, results_per_page=None):
        self.load_all = load_all
        self.form_class = form_class
        self.searchqueryset = searchqueryset

        if form_class is None:
            self.form_class = ModelSearchForm

        if not results_per_page is None:
            self.results_per_page = results_per_page

        if template:
            self.template = template

    def __call__(self, request):
        """
        Generates the actual response to the search.

        Relies on internal, overridable methods to construct the response.
        """
        self.request = request

        self.form = self.build_form()
        self.query = self.request.GET.get("q")
        self.results = self.get_results()

        return self.create_response()

    def build_form(self, form_kwargs=None):
        """
        Instantiates the form the class should use to process the search query.
        """
        data = None
        kwargs = {
            'load_all': self.load_all,
        }
        if form_kwargs:
            kwargs.update(form_kwargs)

        if len(self.request.GET):
            data = self.request.GET

        if self.searchqueryset is not None:
            kwargs['searchqueryset'] = self.searchqueryset

        return self.form_class(data, **kwargs)

    def get_query(self):
        """
        Returns the query provided by the user.

        Returns an empty string if the query is invalid.
        """
        if self.form.is_valid():
            return self.form.cleaned_data['q']

        return ''

    def get_results(self):
        """
        Fetches the results via the form.

        Returns an empty list if there's no query to search with.
        """
        return self.form.search()

    def build_page(self):
        """
        Paginates the results appropriately.

        In case someone does not want to use Django's built-in pagination, it
        should be a simple matter to override this method to do what they would
        like.
        """
        try:
            page_no = int(self.request.GET.get('page', 1))
        except (TypeError, ValueError):
            raise Http404("Not a valid number for page.")

        if page_no < 1:
            raise Http404("Pages should be 1 or greater.")

        start_offset = (page_no - 1) * self.results_per_page
        self.results[start_offset:start_offset + self.results_per_page]

        paginator = Paginator(self.results, self.results_per_page)

        try:
            page = paginator.page(page_no)
        except InvalidPage:
            raise Http404("No such page!")

        return (paginator, page)

    def extra_context(self):
        """
        Allows the addition of more context variables as needed.

        Must return a dictionary.
        """
        return {}

    def get_context(self):
        (paginator, page) = self.build_page()
        print(paginator.num_pages)
        print(page.number)
        page.num_pages = paginator.num_pages
        search = True
        tj_book = []
        if not page.object_list:
            search = ""
            # 随机推荐小说
            num = random.randint(0, 9)
            # 0代表最新
            if num == 0:
                tj_book = Book.objects.all().order_by('-creat_time')[:6]
            else:
                tj_book = Book.objects.filter(group_id=num)[:6]
        right_tj = Book.objects.all().order_by("-creat_time")
        pg = Paginator(right_tj, 6)
        right_tj = pg.page(pg.num_pages - 1).object_list
        context = {
            'query': self.query,
            'form': self.form,
            "book": page.object_list,
            "tj_book": tj_book,
            'page': page,
            'paginator': paginator,
            'suggestion': None,
            "search": search,
            "right_tj": right_tj,
        }

        if hasattr(self.results, 'query') and self.results.query.backend.include_spelling:
            context['suggestion'] = self.form.get_suggestion()

        context.update(self.extra_context())

        return context

    def create_response(self):
        """
        Generates the actual HttpResponse to send back to the user.
        """

        context = self.get_context()

        return render(self.request, self.template, context)
